#include"Quene.h"

void QueueInit(Queue* q) {
	assert(q); 
	q->front = q->rear = NULL; 
	q->NumSize = 0; 
}

void QueuePush(Queue* q, QDataType data) {
	assert(q);
	QNode* NewNode = (QNode*)malloc(sizeof(QNode)); 
	if (!NewNode) { 
		perror("malloc"); 
		exit(-1); 
	}
	NewNode->data = data; 
	NewNode->next = NULL; 

	if (!q->front&&!q->rear) {
		q->front = q->rear = NewNode;
	}
	else {
		q->rear->next = NewNode;
		q->rear = NewNode;
	}
	q->NumSize++;
}

void QueuePop(Queue* q) {
	assert(q);
	if (QueueEmpty(q)) return;
	
	if (QueueSize(q) == 1) {
		free(q->front);
		q->front = NULL;
		q->rear = NULL;
		q->NumSize--;
	}
	else {
		QNode* NewFront = q->front->next;
		free(q->front);
		q->front = NewFront;
		q->NumSize--;
	}

}

QDataType QueueFront(Queue* q) {
	assert(q);
	assert(q->NumSize > 0);
	return q->front->data;
}

QDataType QueueBack(Queue* q) {
	assert(q);
	assert(q->NumSize > 0);
	return q->rear->data;
}

int QueueSize(Queue* q) {
	assert(q);
	return q->NumSize;
}

int QueueEmpty(Queue* q) {
	assert(q);
	if (q->NumSize == 0) return 1;
	else return 0;
}

void QueueDestroy(Queue* q) {
	assert(q);
	if (QueueEmpty(q)) return;
	while (q->front) {
		QNode* pdel = q->front->next;
		free(q->front);
		q->front = pdel;
	}
	q->rear = NULL;
	q->NumSize = 0;
}